package com.video.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.video.common.constant.ServerConstant;
import com.video.common.dto.VideoDto;
import com.video.common.dto.VideoIdListDto;
import com.video.common.lang.Result;
import com.video.entity.FileEntity;
import com.video.entity.User;
import com.video.entity.Video;
import com.video.service.UserService;
import com.video.service.VideoService;
import com.video.service.impl.FileEntityService;
import com.video.util.FetchVideoCover;
import com.video.util.ShiroUtils;
import com.video.util.VideoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author maomao
 */
@Slf4j
@RestController
@RequestMapping("/video")
public class VideoController {

    @Resource
    private VideoService videoService;

    @Resource
    private UserService userService;

    @Resource
    private FileEntityService fileEntityService;

    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        VideoDto video = videoService.getVideo(id);

        Assert.notNull(video, "视频不存在");

        return Result.success(200, "操作成功", video);
    }

    @RequiresAuthentication
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable(name = "id") Long id){

        Video video = videoService.getById(id);

        Long userId = ShiroUtils.getProfile().getId();

        Assert.isTrue(video.getUserId().longValue() == userId.longValue(), "没有权限删除");

        video.setIsVld(0);

        videoService.updateById(video);

        User user = userService.getById(userId);

        Integer videoCount = user.getVideoCount();

        user.setVideoCount(videoCount - 1);

        userService.updateById(user);

        return Result.success(200, "操作成功", null);
    }

    @RequiresAuthentication
    @PostMapping("/modify")
    public Result modify(@RequestBody VideoDto videoDto){
        Assert.isTrue(videoDto.getUserId().longValue() == ShiroUtils.getProfile().getId().longValue(), "没有权限修改");
        Video tempVideo = new Video();
        BeanUtil.copyProperties(videoDto, tempVideo, "createTime, updateTime");
        videoService.updateById(tempVideo);
        return Result.success(200, "操作成功", null);
    }

    @RequiresAuthentication
    @PostMapping("/upload")
    public Result upload(MultipartFile[] files, Long industryId, Long categoryId, String productName, Integer platformId) {

        // 用户Id
        Long userId = ShiroUtils.getProfile().getId();

        // 在数据库中保存的视频路径和封面路径
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;

        // 文件上传的最终保存路径
        String finalVideoPath = "";

        try {
            if (files != null && files.length > 0) {
                List<Video> videoList = new LinkedList<>();
                for (MultipartFile multipartFile : files) {

                    inputStream = multipartFile.getInputStream();

                    String md5 = SecureUtil.md5(inputStream);

                    int videoCount = videoService.count(new QueryWrapper<Video>().eq("md5", md5).eq("is_vld", 1));
                    String originalFilename = multipartFile.getOriginalFilename();

                    if (videoCount != 0){
                        log.info("video file {} already exist", originalFilename);
                        continue;
                    }

                    if (StringUtils.isNotBlank(originalFilename)) {

                        FileEntity videoEntity = fileEntityService.addFileEntity(multipartFile);

                        if (videoEntity != null) {
                            Video video = new Video();
                            Long maxVideoId = videoService.getMaxVideoId();
                            String videoId = VideoUtil.getVideoId(maxVideoId);
                            video.setVideoId(videoId);
                            video.setUserId(userId);
                            video.setVideoName(videoEntity.getEntityName());
                            video.setVideoPath(videoEntity.getDownloadUrl());
                            video.setProductName(productName);
                            video.setPlatformId(platformId);
                            video.setIndustryId(industryId);
                            video.setCategoryId(categoryId);
                            video.setMd5(md5);
                            videoService.save(video);
                            videoList.add(video);
                        }
                    }
                }

                User user = userService.getById(userId);
                User tmp = new User();
                tmp.setId(user.getId());
                tmp.setVideoCount(user.getVideoCount() + videoList.size());
                userService.updateById(tmp);

            } else {
                return Result.fail("请选择文件上传");
            }
        } catch (IOException e) {
            log.info("upload file error: {}", e.getLocalizedMessage());
            return Result.fail(e.getLocalizedMessage());
        }

        return Result.success(200, "操作成功", null);
    }

    @RequiresAuthentication
    @GetMapping("/user/upload")
    public Result getUploadVideo(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "10") Integer pageSize, String keyword) {
        // 用户Id
        Long userId = ShiroUtils.getProfile().getId();

        Page<VideoDto> page = new Page<>(currentPage, pageSize);

        IPage<VideoDto> videoList = videoService.getUserUploadVideo(page, userId, keyword);

        return Result.success(200, "操作成功", videoList);
    }

    @RequiresAuthentication
    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage, @RequestParam(defaultValue = "20") Integer pageSize, Integer categoryId, Integer industryId, Integer platformId, String keyWord) {

        Page<VideoDto> videoDtoPage = new Page<>(currentPage, pageSize);

        IPage<VideoDto> videoDtoList = videoService.listVideo(videoDtoPage, categoryId, industryId, platformId, keyWord);

        return Result.success(videoDtoList);
    }
}
